package com.lcf;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * Created by lancf on 2019/5/8.
 */
public class TestNio {

    @Test
    public void test1() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------put--------------");
        buffer.put("abcde".getBytes());
        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------切换到读取模式--------------");
        buffer.flip();
        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------get--------------");
        byte[] bytes = new byte[buffer.limit()];
        ByteBuffer byteBuffer = buffer.get(bytes);
        System.out.println(new String(bytes, 0, bytes.length));

        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

    }


    @Test
    public void test2() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------put--------------");
        buffer.put("abcde".getBytes());
        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------切换到读取模式--------------");
        buffer.flip();
        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

        System.out.println("-------------get--------------");
        byte[] bytes = new byte[buffer.limit()];
        ByteBuffer byteBuffer = buffer.get(bytes);
        System.out.println(new String(bytes, 0, bytes.length));

        System.out.println("position: " + buffer.position());
        System.out.println("limit: " + buffer.limit());
        System.out.println("capacity: " + buffer.capacity());

    }
}
